package com.tanhua.dubbo.api.Impl;

import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mogo.Comment;
import com.tanhua.model.mogo.Movement;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class CommentApiImpl implements CommentApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 发布动态评论
     */
    @Override
    public Integer Release(Comment comment1) {
        //查询动态表，获取动态发布者id
        ObjectId publishId = comment1.getPublishId();
        Movement movement = mongoTemplate.findById(publishId, Movement.class);
        if (movement != null) {
            comment1.setPublishUserId(movement.getUserId());
        }
        //保存动态评论表
        mongoTemplate.save(comment1);
        //更新动态表中评论的数量
        Query query = Query.query(Criteria.where("id").is(comment1.getPublishId()));
        Update update = new Update();
        //判断是何种操作
        if (comment1.getCommentType() == CommentType.COMMENT.getType()) {
            //评论
            update.inc("commentCount", 1);
        } else if (comment1.getCommentType() == CommentType.LIKE.getType()) {
            //点赞
            update.inc("likeCount", 1);
        } else if (comment1.getCommentType() == CommentType.LOVE.getType()) {
            //喜欢（关注）
            update.inc("loveCount", 1);
        }
        //设置返回最新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);
        Movement modify = mongoTemplate.findAndModify(query, update, options, Movement.class);
        //返回最新数量
        Integer count = modify.statisCount(comment1.getCommentType());
        return count;
    }

    /**
     * 分页查询评论详情
     */
    @Override
    public List<Comment> Lookup(Integer page, Integer pagesize, String movementId, CommentType commentType) {
        //设置查询及分页条件
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(movementId))
                .and("commentType").is(commentType.getType()))
                .skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        //返回查询结果
        return mongoTemplate.find(query, Comment.class);
    }
}
